import MenuConfig from '@/config/menuConfig'
// 引入方法
import { switchMenu } from '@/store/actions'
import { Menu } from 'antd';
import React, { Component } from "react";
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom'
import { Dispatch } from 'redux';
import './index.less'
import { IMenuData, IProps, IState } from './types';// interface 接口


const { SubMenu } = Menu;

// redux 数据部分
const mapStateToProps = (state: Typings.StoreState) => ({
  // tutor: state.tutor.user,
});

// action 操作部分
const mapDispatchToProps = (dispatch: Dispatch<Typings.IndexActions>) => ({
  // verifyUser: (params: Typings.VerifyParmas) => dispatch(UserActions.verifyUser(params)),
  switchMenus: (params: string) => dispatch(switchMenu(params))
});

@(connect(mapStateToProps, mapDispatchToProps) as any)
export default class NavLeft extends Component<IProps, IState> {

  public state: IState
  constructor(props: Readonly<IProps>) {
    super(props);
    this.state = {
      currentKey: [], // 选中的key
      menuTreeNode: null, // 列表数据，处理好的组件数据
      selectekey: ['/admin/home'], // 初始化选择
    };
  }

  public componentDidMount() {
    
    const menuTreeNode = this.renderMenu(MenuConfig)
    const currentKey = window.location.pathname;
    const data =  currentKey.length< 7 ? '/admin/home' : currentKey
    this.setState({
      currentKey: [data],
      menuTreeNode
    })
  }

  /**
   * 菜单点击
   */
  public handleClick = ({ item, key }: { item: any, key: string }) => {
    // if (key == this.state.currentKey) {
    //   return false;
    // }
    this.setState({
      currentKey:[key]
    });
    // 获取方法，action
    const { switchMenus } = this.props;
    switchMenus(item.props.title)
  }

  /**
   * 菜单渲染,做一个循环递归
   * @param {Array} data 菜单数据
   */
  public renderMenu = (data: any[]): any => {
    return data.map((item: IMenuData) => {
      if (item.children) { // 判断子节点生成submenu
        return (
          <SubMenu title={ item.title } key={ item.key }>
            { this.renderMenu(item.children) }
          </SubMenu>
        )
      }
      return <Menu.Item title={ item.title } key={ item.key }>
        <NavLink to={ item.key }>{ item.title }</NavLink>
      </Menu.Item>
    })
  }

  public render() {
    return (
      <div>
        <div className="logo">
          <img src="/assets/logo-ant.svg" alt="" />
          <h1>Imooc MS</h1>
        </div>
        {/* 一个树列表 */ }
        <Menu theme='dark' selectedKeys={ this.state.currentKey}  defaultSelectedKeys={ this.state.selectekey } onClick={ this.handleClick } mode="vertical">
          { this.state.menuTreeNode }
        </Menu>
      </div >
    )
  }
}